<template>
  <div class="chart" ref="initChart" v-loading="loading">
    
  </div>
</template>

<script>

import { getUpAndDownRanking } from '@/api/home'

export default {
  name: 'upsAndDownsRanking',
  props: ['upAndDownMessage', ],
  data() {
    return {
      typeValue: 0,
      loading: true,
      retuenData: null,
      priceArr: [],
      thisDataArr: [],
      lastDataArr: [],
      productNameArr: [],
      unitMeasureArr: [],
    };
  },
  watch: {
    upAndDownMessage: {
      //对象中的属性发生变化，deep（是深度监听）设为true
      deep: true,
      //执行监听到的数据v（从父组件异步过来的数据）
      handler(newVal) {
        this.loading = true
        this.getUpAndDownRankingData(newVal)
        this.typeValue = newVal;
      }
    }
  },
  mounted() {
    this.getUpAndDownRankingData()
  },
  methods: {
    getUpAndDownRankingData(type) {
      getUpAndDownRanking().then(res => {
        // 0跌 1涨
        this.reduction()
        if (type === 0) {
          this.retuenData = res.data[0]
        } else {
          this.retuenData = res.data[1]
        }
        this.priceArr = [];
        this.thisDataArr = [];
        this.lastDataArr = [];
        this.retuenData.forEach(item => {
          this.priceArr.push(item.price);
          this.productNameArr.push(item.productName);
          this.thisDataArr.push(item.thisData);
          this.lastDataArr.push(item.lastData);
          this.unitMeasureArr.push(item.unitMeasure)
        })
        this.initChart(this.typeValue)
        this.loading = false;
      })
    },
    initChart(typeValue) {
      var myChart = this.$echarts.getInstanceByDom(
          this.$refs.initChart
      );
      // 防止重复初始化
      if (myChart == null) {
        myChart = this.$echarts.init(this.$refs.initChart);
      }
      myChart.clear()
      // 绘制图表配置
      myChart.setOption({
        // 设置echarts图标的位置，边距
        grid: {
          left: "12%",
          right: "60px",
        },
        // 设置鼠标移入柱状图提示框
        tooltip: {
          trigger: "axis",
          // 鼠标移入时中线虚线的隐藏
          axisPointer: {
            type: "cross",
          },
          // 提示框显示内容
          formatter: function (params) {
            var str = typeValue === 0 ? '跌幅: ' : '涨幅: '
            //console.log(params)
            return `<b>产品：${params[0].name}<br/>${str}${params[0]["data"].value}%<br/>
                             今日价格：${params[0]["data"].thisData} ${params[0]["data"].unitMeasure}<br/>
                             昨日价格：${params[0]["data"].lastData} ${params[0]["data"].unitMeasure}<br/>`;
          },
        },
        backgroundColor: "#f4fdfa",
        barWidth: 15,
        xAxis: {
          type: "value",
          splitLine: {
            lineStyle: {
              type: "dashed",
            },
          },
          axisTick: {
            show: false,
          },

          axisLabel: {
            //  改变x轴字体颜色和大小
            textStyle: {
              color: "#2c3e50",
              fontSize: 16,
            },
          },
        },
        yAxis: {
          type: "category",
          data: this.productNameArr,
          splitLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            //  改变y轴颜色
            lineStyle: {
              color: "#2c4054",
            },
          },
          axisLabel: {
            textStyle: {
              color: "#2c3e50",
              fontSize: 10,
            },
            // y轴文本内容太长解决方法
            formatter: function (params) {
              var newParamsName = ""; // 最终拼接成的字符串
              var paramsNameNumber = params.length; // 实际标签的个数
              var provideNumber = 7; // 每行能显示的字的个数
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                for (var p = 0; p < rowNumber; p++) {
                  var tempStr = ""; // 表示每一次截取的字符串
                  var start = p * provideNumber; // 开始截取的位置
                  var end = start + provideNumber; // 结束截取的位置
                  // 此处特殊处理最后一行的索引值
                  if (p == rowNumber - 1) {
                    // 最后一次不换行
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    // 每一次拼接字符串并换行
                    tempStr = params.substring(start, end) + "\n";
                  }
                  newParamsName += tempStr; // 最终拼成的字符串
                }
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
              }
              //将最终的字符串返回
              return newParamsName;
            },
          },
        },
        series: [
          {
            type: "bar",
            name: typeValue === 0 ? '跌幅' : '涨幅',
            stack: "Total",
            barWidth: 30,
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  formatter: (typeValue === 0 ? '-' : '+') + "{c}%",
                  position: "right", //在上方显示
                  textStyle: {
                    //数值样式
                    color: "#000",
                    fontSize: 12,
                    fontWeight: 600,
                  },
                },
                color: new this.$echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  {
                    offset: 0,
                    color: "#1abc9c",
                  },
                  {
                    offset: 1,
                    color: "rgba(24,144,255,0)",
                  },
                ]),
                borderRadius: 15,
              },
            },
            // 每个产品的涨跌幅数值
            data: this.getEchartsSeries(),
          },
        ],
      });
      window.addEventListener("resize", function () {
        //监听窗口变动实时渲染
        myChart.resize();
      });
    },
    // 获取涨跌幅排名的series数据
    getEchartsSeries() {
      let series = [];
      for (let i = 0; i < this.priceArr.length; i++) {
        // 返回值中，跌幅为负值，直接用负值会导致图表渲染出问题
        // 这里将price负值变为正值，在图表series配置中填符号
        if (this.priceArr[i] < 0) {
          this.priceArr[i] = -this.priceArr[i];
        }
        series.push({
          value: this.priceArr[i],
          thisData: this.thisDataArr[i],
          lastData: this.lastDataArr[i],
          unitMeasure: this.unitMeasureArr[i], 
        });
      }
      return series;
    },
    reduction() {
      this.retuenData = [],
      this.priceArr = [],
      this.thisDataArr = [],
      this.lastDataArr = [],
      this.productNameArr = [],
      this.unitMeasureArr = []
    }
    
  },
};
</script>

<style lang="less" scoped>
.chart {
  width: 100%;
  height: 100%;
}

</style>